"""
中间件
处理日志、异常、CORS等
"""
from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from utils.logger import app_logger
from utils.api_response import ApiResponseHelper
import time


async def log_middleware(request: Request, call_next):
    """日志中间件"""
    start_time = time.time()

    # 记录请求
    app_logger.info(f"请求开始: {request.method} {request.url.path}")

    # 处理请求
    response = await call_next(request)

    # 记录响应
    duration = time.time() - start_time
    app_logger.info(
        f"请求完成: {request.method} {request.url.path} "
        f"状态码={response.status_code} 耗时={duration:.3f}s"
    )

    return response


async def error_handler_middleware(request: Request, call_next):
    """全局异常处理中间件"""
    try:
        return await call_next(request)
    except Exception as e:
        app_logger.error(f"未捕获的异常: {e}", exc_info=True)
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content=ApiResponseHelper.internal_error(msg=f"系统错误: {str(e)}")
        )


def setup_cors(app):
    """配置CORS"""
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 生产环境应指定具体域名
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
